package com.mengjing.adcommon.ad

import android.content.Context
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTNativeExpressAd

class BannerAd(mContext: Context): BaseAd(mContext) {
    private var mTTAd: TTNativeExpressAd? = null
    private var mBannerContainer: FrameLayout? = null

    /**
     * @param codeId 代码位ID
     * @param bannerContainer banner 容器
     * @param width 宽度
     * @param height 高度
     */
    fun showAd(codeId: String, bannerContainer: FrameLayout, width: Int, height: Int) {
        mCodeId = codeId
        mBannerContainer = bannerContainer

        loadAd(width, height);
    }

    private fun loadAd(width: Int, height: Int) {
        mBannerContainer?.removeAllViews()

        val adSlot = AdSlot.Builder()
                .setCodeId(mCodeId)
                .setAdCount(1)
                .setExpressViewAcceptedSize(width.toFloat(), height.toFloat())
                .build()

        mTTAdNative.loadBannerExpressAd(adSlot, AdListener())
    }

    private inner class AdListener: TTAdNative.NativeExpressAdListener {
        override fun onError(code: Int, messsage: String?) {
            Log.d(TAG, "onError: load error: $code, $messsage")
            mBannerContainer?.removeAllViews()
        }

        override fun onNativeExpressAdLoad(ads: MutableList<TTNativeExpressAd>?) {
            if (ads == null || ads.size == 0) return
            mTTAd = ads[0]
            mTTAd?.setExpressInteractionListener(AdInteractionListener())
            renderAd()
        }
    }

    private inner class AdInteractionListener: TTNativeExpressAd.ExpressAdInteractionListener {
        override fun onAdClicked(p0: View?, p1: Int) {
            Log.d(TAG, "onAdClicked: ")
        }

        override fun onAdShow(p0: View?, p1: Int) {
            Log.d(TAG, "onAdShow: ")
        }

        override fun onRenderFail(p0: View?, p1: String?, p2: Int) {
            Log.d(TAG, "onRenderFail: render error: code: $p2, message: $p1")
        }

        override fun onRenderSuccess(p0: View?, p1: Float, p2: Float) {
            mBannerContainer?.removeAllViews()
            mBannerContainer?.addView(p0)
        }

    }

    private fun renderAd() {
        mTTAd?.render()
    }

    fun destroyAd() {
        mTTAd?.destroy()
    }
}